// pages/admin/menu/menu.js
const app = getApp();
wx.cloud.init();

const db = wx.cloud.database();
const _ = db.command;
const db_menuImg = db.collection('menuImg');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    cloudPath: [],
    fID:'',
    fileList: [

    ],
  },

  del(e) {
    console.log('删除文件', e)
    const delIndex = e.detail.index
    const {
      fileList
    } = this.data
    fileList.splice(delIndex, 1)
    this.setData({
      fileList
    })

  },
  upload(event) {

    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    console.log(file)
    const {
      fileList = []
    } = this.data
    fileList.push({
      ...file,
      url: file.path
    })
    this.setData({
      fileList
    })
    console.log(this.data.fileList)
    this.uploadToCloud()
  },
  parseName(file) {
    var str = file;
    var obj = str.lastIndexOf("/");
    let name = str.substr(obj + 1)
    console.log(str.substr(obj + 1));
    // let name = str.substr(0, obj)
    console.log(name);
    return name;
  },
  // 上传图片
  uploadToCloud() {

    const {
      fileList
    } = this.data;
    if (!fileList.length) {
      wx.showToast({
        title: '请选择图片',
        icon: 'none'
      });
    } else {
      const uploadTasks = []
      for (let i = 0; i < fileList.length; i++) {
        console.log(i, fileList[i])
        uploadTasks.push(this.uploadFilePromise(`my-photo${i}.png`, fileList[i]))

      }
      // const uploadTasks = fileList.map((file, index) => {
      //   console.log(index, file)
      //   this.uploadFilePromise(`my-photo${index}.png`, file)
      // });
      Promise.all(uploadTasks).then(data => {
        console.log(data)
        wx.showToast({
          title: '上传成功',
          icon: 'none'
        });
        const newFileList = data.map(item => {
          url: item.fileID
        })
        console.log(newFileList)
        this.setData({
          cloudPath: data,
          fileList: newFileList
        });
      }).catch(e => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.log(e);
      });
    }
  },
  uploadFilePromise(fileName, chooseResult) {
    return new Promise((resolve, reject) => {
      wx.cloud.uploadFile({
        cloudPath: "menu/" + fileName,
        filePath: chooseResult,
        success: res => {
          resolve(res)
        },
        fail: err => {
          reject(err)
        }
      });
    })
  },
  getMenuImg(callback) {
     return db_menuImg.orderBy('time','desc').limit(1).get({
      success: res => {
        console.log(res)
        callback(res)
        this.setData({
          fID: res.data[0].fileID
        })
      }
    });
  },
getTmpUrl(res) {
    console.log(res.data[0].fileID)
    wx.cloud.getTempFileURL({
      fileList: [res.data[0].fileID],
      success: res => {
        // get temp file URL
        console.log(res.fileList)
        this.setData({
          fileList: res.fileList
        });
      },
      fail: err => {
        // handle error
      }
    })
  },
  //存fileID
  saveFileID(fileID) {
    db_menuImg.add({
      data: {
        fileID: fileID,
        time: new Date(),
        isShow: false
      },
      success: res => {
        console.log('新增记录', res)
        this.getMenuImg(this.getTmpUrl)
      },
      fail: err => {
        console.error('新增失败', err)
      }
    })
  },

  uploadImg() {
    console.log('上传图片到云存储')
    const {
      imgList
    } = this.data;
    if (!imgList.length) {
      wx.showToast({
        title: '请选择图片',
        icon: 'none'
      });
    } else {
      const uploadTasks = []
      for (let i = 0; i < imgList.length; i++) {
        console.log(i, imgList[i])
        uploadTasks.push(this.uploadFilePromise(this.parseName(imgList[i]), imgList[i]))
      }
      // const uploadTasks = fileList.map((file, index) => {
      //   console.log(index, file)
      //   this.uploadFilePromise(`my-photo${index}.png`, file)
      // });
      Promise.all(uploadTasks).then(data => {
        console.log(data)
        wx.showToast({
          title: '上传成功',
          icon: 'none'
        });
        const newFileList = data.map(item => {
          url: item.fileID,
          this.saveFileID(item.fileID)
        })
        console.log(newFileList)
        this.setData({
          cloudPath: data,
          fileList: newFileList
        });
      }).catch(e => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.log(e);
      });
    }

  },
  chooseImage() {
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        if (this.data.imgList.length > 0) {
          this.setData({
            imgList: this.data.imgList.concat(tempFilePaths)
          })
        } else {
          this.setData({
            imgList: tempFilePaths
          })
        }
      }

    })
  },
  viewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  showImg(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.url],
      current: e.currentTarget.dataset.url
    });
  },
  delImg(e) {
    wx.showModal({
      title: '是否确认',
      content: '确定要删除？',
      cancelText: '取消',
      confirmText: '确认',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMenuImg(this.getTmpUrl)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})